import React, { Component } from 'react'
import {
	StyleSheet,
	View,
	Text,
	FlatList,
	RefreshControl,
	ActivityIndicator,
	DeviceInfo
} from 'react-native'
import {
	createMaterialTopTabNavigator,
	createAppContainer
} from 'react-navigation'
import { connect } from 'react-redux'
import Toast from 'react-native-easy-toast'
import NavigationBar from '../common/NavigationBar'
import actions from '../action'
import PopularItem from '../common/PopularItem'
import NavigationUtil from '../navigator/NavigationUtil'
import FavoriteDao from '../expand/dao/FavoriteDao'
import { FLAG_STORAGE } from '../expand/dao/DataStore'
import FavoriteUtil from '../util/FavoriteUtil'
import EventBus from 'react-native-event-bus'
import EventTypes from '../util/EventTypes'

const URL = 'https://api.github.com/search/repositories?q='
const QUERY_STR = '&sort=stars'
const THEME_COLOR = '#678'
const favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular)

export default class PopularPage extends Component {
	constructor(props) {
		super(props)
		this.tabNames = ['Java', 'Android', 'iOS', 'React', 'React Native', 'PHP']
		// this.tabNames = ["Java", "Android"];
	}

	_genTabs() {
		const tabs = {}
		this.tabNames.forEach((item, index) => {
			// tabs[`tabs${index}`] = {
			//   screen: PopularTab,
			//   navigationOptions: {
			//     title: item
			//   }
			// };
			//注意这种写法,给顶部tabbar页面传递参数
			tabs[`tabs${index}`] = {
				screen: props => <PopularTabPage {...props} tabLabel={item} />,
				navigationOptions: {
					title: item
				}
			}
		})
		return tabs
	}

	render() {
		//导航栏
		let statusBar = {
			backgroundColor: THEME_COLOR,
			barStyle: 'light-content'
		}
		let navigationBar = (
			<NavigationBar
				title={'最热'}
				statusBar={statusBar}
				style={{ backgroundColor: THEME_COLOR }}
			/>
		)

		const TabNavigator = createAppContainer(
			createMaterialTopTabNavigator(this._genTabs(), {
				tabBarOptions: {
					tabStyle: styles.tabStyle,
					upperCaseLabel: false, //是否使标签大写，默认为true
					scrollEnabled: true, //是否支持选项卡滚动，默认为false
					style: {
						backgroundColor: '#678', //Tab的背景色
						height: 30 //fix开启scrollEnabled后再加Android上初次加载时闪烁问题
					},
					indicatorStyle: styles.indicatorStyle, //标签指示器的样式
					labelStyle: styles.labelStyle //文字的样式
				}
			})
		)

		//注意这里需要将View的样式用flex（踩坑）
		return (
			<View
				style={{
					flex: 1,
					marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0
				}}
			>
				{navigationBar}
				<TabNavigator />
			</View>
		)
	}
}

const pageSize = 10

class PopularTab extends Component {
	constructor(props) {
		super(props)
		const { tabLabel } = this.props
		this.storeName = tabLabel
		this.isFavoriteChanged = false
	}

	componentDidMount() {
		this.loadData()

		//监听收藏页面最热tab下的数据变动
		EventBus.getInstance().addListener(
			EventTypes.favorite_changed_popular,
			(this.favoriteChangeListener = () => {
				this.isFavoriteChanged = true
			})
		)
		//监听底部tabBar切换
		EventBus.getInstance().addListener(
			EventTypes.bottom_tab_select,
			(this.bottomTabSelectListener = data => {
				if (data.to === 0 && this.isFavoriteChanged) {
					console.log('333')
					this.loadData(null, true)
					this.isFavoriteChanged = false
				}
			})
		)
	}

	componentWillUnmount() {
		EventBus.getInstance().removeListener(this.favoriteChangeListener)
		EventBus.getInstance().removeListener(this.bottomTabSelectListener)
	}

	loadData(loadMore, refreshFavorite) {
		const {
			onRefreshPopular,
			onLoadMorePopular,
			onFlushPopularFavorite
		} = this.props
		const store = this._store()
		const url = this.genFetchUrl(this.storeName)
		if (loadMore) {
			onLoadMorePopular(
				this.storeName,
				++store.pageIndex,
				pageSize,
				store.items,
				favoriteDao,
				callback => {
					this.refs.toast.show('没有更多了' + callback)
				}
			)
		} else if (refreshFavorite) {
			onFlushPopularFavorite(
				this.storeName,
				store.pageIndex,
				pageSize,
				store.items,
				favoriteDao
			)
		} else {
			onRefreshPopular(this.storeName, url, pageSize, favoriteDao)
		}
	}

	genFetchUrl(key) {
		return URL + key + QUERY_STR
	}

	/**
	 * 获取与当前页面有关的数据
	 * @return {*}
	 * @private
	 */
	_store() {
		const { popular } = this.props
		let store = popular[this.storeName]
		if (!store) {
			store = {
				items: [],
				isLoading: false,
				projectModels: [], //要显示的数据
				hideLoadingMore: true //默认隐藏加载更多
			}
		}
		return store
	}

	renderItem(data) {
		const item = data.item
		// return (
		//   <View style={{ marginBottom: 10 }}>
		//     <Text style={{ backgroundColor: "#faa" }}>{JSON.stringify(item)}</Text>
		//   </View>
		// );
		return (
			<PopularItem
				projectModel={item}
				onSelect={callback => {
					NavigationUtil.goPage(
						{
							projectModel: item,
							flag: FLAG_STORAGE.flag_popular,
							callback
						},
						'DetailPage'
					)
				}}
				onFavorite={(item, isFavorite) =>
					FavoriteUtil.onFavorite(
						favoriteDao,
						item,
						isFavorite,
						FLAG_STORAGE.flag_popular
					)
				}
			/>
		)
	}

	getIndicator() {
		return this._store().hideLoadingMore ? null : (
			<View style={styles.indicatorContainer}>
				<ActivityIndicator style={styles.indicator} />
				<Text>正在加载更多</Text>
			</View>
		)
	}

	render() {
		//这里的popular就是mapStateToProps中订阅的
		// const { popular } = this.props;
		// let store = popular[this.storeName]; //动态获取state
		// //给store做一个补偿（设置默认值）
		// if (!store) {
		//   store = {
		//     items: [],
		//     isLoading: false
		//   };
		// }
		let store = this._store()

		return (
			<View style={styles.container}>
				<FlatList
					data={store.projectModels}
					renderItem={data => this.renderItem(data)}
					keyExtractor={item => '' + item.item.id}
					refreshControl={
						<RefreshControl
							title={'Loading'}
							titleColor={THEME_COLOR}
							colors={[THEME_COLOR]}
							refreshing={store.isLoading}
							onRefresh={() => this.loadData()}
							tintColor={THEME_COLOR}
						/>
					}
					ListFooterComponent={() => this.getIndicator()}
					onEndReached={() => {
						//这里需要解决FlatList触底刷新会触发多次的问题(刚进入页面会触发，但是不需要加载更多数据)
						// console.log("---onEndReached---");
						//确保加载更多数据是在onMomentumScrollBegin中设置了this.canLoadMore之后
						setTimeout(() => {
							if (this.canLoadMore) {
								console.log('---onEndReached---')
								this.loadData(true)
								this.canLoadMore = false
							}
						}, 100)
					}}
					onEndReachedThreshold={0.5}
					onMomentumScrollBegin={() => {
						//fix初始化滚动页面调用onEndReached的问题（只有在滚动的时候才允许加载更多数据）
						this.canLoadMore = true
						console.log('---onMomentumScrollBegin---')
					}}
				/>
				<Toast ref={'toast'} position={'center'} />
			</View>
		)
	}
}

//订阅
//组件只需要关心与自己有关的state
const mapStateToProps = state => ({
	popular: state.popular
})
const mapDispatchToProps = dispatch => ({
	onRefreshPopular: (storeName, url, pageSize, favoriteDao) =>
		dispatch(actions.onRefreshPopular(storeName, url, pageSize, favoriteDao)),
	onLoadMorePopular: (
		storeName,
		pageIndex,
		pageSize,
		items,
		favoriteDao,
		callback
	) =>
		dispatch(
			actions.onLoadMorePopular(
				storeName,
				pageIndex,
				pageSize,
				items,
				favoriteDao,
				callback
			)
		),
	onFlushPopularFavorite: (
		storeName,
		pageIndex,
		pageSize,
		items,
		favoriteDao
	) =>
		dispatch(
			actions.onFlushPopularFavorite(
				storeName,
				pageIndex,
				pageSize,
				items,
				favoriteDao
			)
		)
})

//注意：connect只是个function，并不一定非要放在export后面
const PopularTabPage = connect(
	mapStateToProps,
	mapDispatchToProps
)(PopularTab)

const styles = StyleSheet.create({
	container: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: '#f5fcff'
	},
	welcome: {
		fontSize: 16
	},
	tabStyle: {
		// minWidth: 50 //加载慢的时候会出现样式错乱，这里注释掉
		padding: 0
	},
	indicatorStyle: {
		height: 2,
		backgroundColor: '#fff'
	},
	labelStyle: {
		fontSize: 13,
		margin: 0
	},
	indicatorContainer: {
		alignItems: 'center'
	},
	indicator: {
		color: 'red',
		margin: 10
	}
})
